package nix.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 代理对象工厂
 */
public class ProxyFactory {

	private Object targetObject;// 目标对象

	private BeforeAdvice beforeAdvice;// 前置增强

	private AfterAdvice afterAdvice;// 后置增强

	/**
	 * 生成代理对象
	 */
	public Object createProxy() {

		ClassLoader loader = this.getClass().getClassLoader();
		// 获得目标对象实现的接口
		Class[] interfaces = targetObject.getClass().getInterfaces();
		// 调用处理器
		InvocationHandler h = new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// 前置增强
				if (beforeAdvice != null) {
					beforeAdvice.before();
				}
				// 调用目标方法
				method.invoke(targetObject, args);
				// 后置增强
				if (afterAdvice != null) {
					afterAdvice.after();
				}
				return null;
			}
		};
		// 创建返回代理对象
		return Proxy.newProxyInstance(loader, interfaces, h);
	}

	public Object getTargetObject() {
		return targetObject;
	}

	public void setTargetObject(Object targetObject) {
		this.targetObject = targetObject;
	}

	public BeforeAdvice getBeforeAdvice() {
		return beforeAdvice;
	}

	public void setBeforeAdvice(BeforeAdvice beforeAdvice) {
		this.beforeAdvice = beforeAdvice;
	}

	public AfterAdvice getAfterAdvice() {
		return afterAdvice;
	}

	public void setAfterAdvice(AfterAdvice afterAdvice) {
		this.afterAdvice = afterAdvice;
	}
}
